package com.eco.fanliapp.job.hdkitemjob;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.*;
import com.eco.fanliapp.vo.HaoDanKuItemInfo;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;


@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class getFullHDKItemsTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(getFullHDKItemsTask.class);
    @Autowired
    private IJobOrderInfoGetService jobOrderInfoGetService;
    @Autowired
    private IAppGoodsService appGoodsService;

    @Autowired
    private IUserCashschemeService userCashschemeService;

    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;

    public getFullHDKItemsTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执获取好单库商品列表定时任务-getFullHDKItemsTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        CountLauncher countLauncher = new CountLauncher(10);
        jobOrderInfoGetService.setCountLauncher(countLauncher);
        log.info("开始获取好单库商品开始  0 * */1 * * ?");
        long startMillions = System.currentTimeMillis();
        long back = 500;
//        int intArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17};
        int intArray[] = {10, 11, 4, 1, 9, 3, 2, 6, 12, 15, 5, 7, 8, 13, 16, 17};

        for (int y = 0; y < intArray.length; y++) {
            int n = 0;
            long min = 1;
            List<AppGoods> addAppGoodsList = new ArrayList<>();
            Map map = new HashMap<>();
//            appGoodsMapper.updateGoods("10000", null, intArray[y]);
            while (true) {

                Map<String, Object> data = new HashMap<String, Object>();
                data.put("nav", "3");
                data.put("back", back);
                data.put("min_id", min);
//                data.put("sort", 0);
                data.put("sort", 11);
                data.put("cid", intArray[y]);

                try {
                    String str = ApiUtils.getData(ApiEnum.ITEMLIST, data);

//                log.info("获取好单库商品列表数据{}", str);
                    JSONObject object = JSONObject.parseObject(str);
                    AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
                    if (response != null && response.getCode() == 1) {  //code等于1代表请求成功
                        JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
                        List<HaoDanKuItemInfo.DataBean> bean = JsonUtils.getJsonToList(array.toJSONString(), HaoDanKuItemInfo.DataBean.class);
                        if (bean == null || bean.size() <= 0) {
                            break;
                        }
//                        AppCompany com = userCashschemeService.findCompanyAll();
//                        List<AppGoods> updateAppGoodsList = new ArrayList<>();
//                        List<AppGoods> addAppGoodsList = new ArrayList<>();
                        for (HaoDanKuItemInfo.DataBean haoDanKuItemInfo : bean) {
                            AppGoods dataBean = HDKUtils.getAppGoodsFromHDK(haoDanKuItemInfo);
                            String tkMoney_ =
                                    BigDecimalUtils.FanliMoney(dataBean.getTkrates(),
                                            new BigDecimal(dataBean.getItemendprice())).toString();
                            dataBean.setTkmoney(tkMoney_);
                            dataBean.setFanliUpdateTime((System.currentTimeMillis()) + "");
//                            dataBean = appGoodsService.getMoneyInfoByGoodsId(com, dataBean);
                            dataBean.setItemType(1);
//                            //判断是否最终金额小于0
                            BigDecimal itemendprice = new BigDecimal(dataBean.getItemendprice() == null ? 0d : dataBean.getItemendprice());
                            BigDecimal tkMoney = new BigDecimal(dataBean.getTkmoney() == null ? "0" : dataBean.getTkmoney());
                            if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                                continue;
                            }
                            dataBean.setCreateTime(DateUtils.getNowTimestamp());
                            dataBean.setUpdateTime(DateUtils.getNowTimestamp());
                            dataBean.setAddUserId(-115);
                            dataBean.setSort(n++);
                            addAppGoodsList.add(dataBean);
//                            AppGoods appGoods = appGoodsMapper.findAppGoodsByItemId(dataBean.getItemid());
//                            if (appGoods != null) {
//                                if (appGoods.getItemTop() == 1 && appGoods.getDeleted() == 0) {
//                                    if (appGoods.getRecommend() != 1) {
//                                        dataBean.setSort(n++);
//                                    }
//                                    updateAppGoodsList.add(dataBean);
//                                } else {
//                                    continue;
//                                }
//                            } else {
//                                dataBean.setSort(n++);
//                                addAppGoodsList.add(dataBean);
//                            }
////                        }
//                        }
//
//                        if (addAppGoodsList.size() > 0) {
//                            try {
//                                boolean flag = appGoodsService.saveBatch(addAppGoodsList);
//                                if (flag) {
//                                    log.info("商品拉取API   入库商品新增成功 size=" + addAppGoodsList.size());
//                                    //添加索引
////                            for (AppGoods goods : addAppGoodsList) {
////                                appGoodsService.updateIndex(goods, "add");
////                            }
//                                } else {
//                                    log.info("商品拉取API   入库商品新增失败" + addAppGoodsList.toString());
//                                }
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                        if (updateAppGoodsList.size() > 0) {
//                            for (AppGoods goods : updateAppGoodsList) {
//                                try {
//                                    int i = appGoodsService.updateBatchByItemId(goods);
//                                    if (i > 0) {
//                                        log.info("商品拉取API   入库商品更新成功 数据size={} ", updateAppGoodsList.size());
//                                        //添加索引
////                                appGoodsService.updateIndex(goods, "update");
//                                    } else {
//                                        log.info("商品拉取API   入库商品更新失败 数据={} ", updateAppGoodsList.toString());
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
                        }

                    } else {
                        log.info("商品拉取API   请求失败{}", response.getMsg());
                        break;
                    }
                    if (response.getMinId() != null) {
                        min = response.getMinId();
                    } else {
                        break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("商品拉取API   0 0/3 * * * ? 失败 耗时" + (System.currentTimeMillis() - startMillions) + "   错误=" + e.getMessage());
                    break;
                }
            }
            int mo = addAppGoodsList.size() % 40;
            int pageNum = addAppGoodsList.size() / 40;
            int pageSize = 40;
            if (mo > 0) {
                pageNum += 1;
            }
            if (addAppGoodsList != null && addAppGoodsList.size() > 0) {

                for (int i = 1; i <= pageNum; i++) {
//                    Map pageMap = new HashMap<>();
                    List<AppGoods> pageAppGoodsList = new ArrayList<>();
                    int currIdx = (i > 1 ? (i - 1) * pageSize : 0);
                    for (int k = 0; k < pageSize && k <= addAppGoodsList.size() - currIdx - 1; k++) {
                        AppGoods appGoods = addAppGoodsList.get(currIdx + k);
                        pageAppGoodsList.add(appGoods);
                    }
//                    String classifiyKey = "app_classifyGoodsLists_" + i;
                    map.put(i, pageAppGoodsList);
                }
                String key = "app_classify_" + intArray[y];
                redisTemplateService.set(key, map, 0);
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束获取好单库商品列表定时任务-getFullHDKItemsTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - beginTime));

    }
}

